package chapter1;

import java.util.Iterator;

public class LinkedQueue<T> implements Queue<T> {
    private int index;
    private Node<T> head = null;
    private Node<T> last = null;

    @Override
    public void enqueue(T item) {
        if (item == null) {
            new NullPointerException("item cannot be null");
        }
        Node<T> oldLast = last;
        last = new Node<>();
        last.setItem(item);
        last.setNext(null);
        if (isEmpty()) {
            head = last;
        } else {
            oldLast.setNext(last);
        }
        index++;
    }

    @Override
    public T dequeue() {
        if (isEmpty()) {
            return null;
        }

        Node<T> oldHead = head;
        head = head.getNext();
        index--;
        if (isEmpty()) {
            last = null;
        }
        return oldHead.getItem();
    }

    @Override
    public boolean isEmpty() {
        return index == 0;
    }

    @Override
    public int size() {
        return index;
    }

    @Override
    public Iterator<T> iterator() {
        return new LinkedIterator<>(head);
    }
}
